package com.yuhan.common.base;

import com.yuhan.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import java.io.Serializable;
import java.util.List;


/**
 * @program: yunpi-credit-parent
 * @description:
 * @author: hejing
 * @create: 2019-08-03 15:07
 **/
public abstract class BaseService<D extends BaseRepository, T extends BaseEntity> {
    @Autowired
    private D baseDao;

    public R findById(Serializable id) {
        return R.ok(baseDao.findById(id));
    }

    public R saveOrUpdate(T entity) {
        baseDao.save(entity);
        return R.ok(entity);
    }

    public R deleteById(Serializable id) {
        if (id != null) {
            baseDao.deleteById(id);
            return R.ok(id);
        } else {
            return R.error("删除记录id不能为空！");
        }
    }

    public R deleteAll(List<String> ids) {
        for (String id : ids) {
            baseDao.deleteById(id);
        }
        return R.ok();
    }

    public T findOne(Serializable id) {
        return (T) baseDao.getOne(id);
    }

    public List<T> findAll(T baseEntity) {
        return baseDao.findAll(Example.of(baseEntity));
    }
}
